$(function(){
	$('.date').each(function(index,element){
		$(this).datepicker({
	      changeMonth: true,
	      changeYear: true,
	      dateFormat: 'yy-mm-dd'
	    });
		$(this).on("change", function(event){
			var temp = $("input[name='zxdk_"+index+"']").val();
			if(temp != ''&& temp != null){
				var dateTime = new moment(temp);
				var wlxd = parseDate2String(dateTime);
				var id = $('#id_'+index).text();
				$("input[name='wlxd_"+index+"']").val(wlxd);
				var zxys = parseDate2String(dateTime.add(20,'d'));
				$("input[name='zxys_"+index+"']").val(zxys);
				var ky = parseDate2String(dateTime.add(25,'d'));
				$("input[name='ky_"+index+"']").val(ky);
				$.ajax({
				    type: "POST",
				    url: "/merchant/updateDateTime",
				    data: {zhuangxiuTime:temp,wliaoxiadanTime:wlxd,zxiuyanshouTime:zxys,kaiyeTime:ky,id:id},
				    success: function (data) {
				        if(data.success){
				            
				        }else{
				            
				        }
				    },
				    dataType: "json"
				});
			}
	    });
	})
	var dialog, form, activityDialog,activityForm,
    allFields = $([]).add(merchantName).add(merchantNo).add(accountName).add(shopName),
    tips = $(".validateTips"),activityElement = null;
	
	dialog = $("#dialog-form").dialog({
	  autoOpen: false,
      height: 450,
      width: 400,
      modal: true,
      buttons: {
    	  "确定": addUser,
    	  '取消': function() {
    		  dialog.dialog("close");
        }
      },
      close: function() {
    	  form[0].reset();
        allFields.removeClass("ui-state-error");
      }
    });
	form = dialog.find("form");
	$("#create-user").button().on( "click", function() {
		dialog.dialog("open");
	});
	$("#activity-done-radio").checkboxradio({icon:false});
	$("#activity-not-done-radio").checkboxradio({icon:false});
	activityDialog = $("#activity-form").dialog({
		autoOpen: false,
		modal: true,
		close: function() {
//			activityForm.reset();
		},
		buttons: {
			"确定": addactivity,
			'取消': function() {
				activityDialog.dialog("close");
			}
	    }
	});
	function addactivity(element){
		$.ajax({ type: 'POST', data: $("#activityForm").serialize(), url: $("#activityForm").attr('action'),dataType: "json",
	        success: function (data) {
	        	if(data.success){
	        		var done = data.message;
	        		alert(activityElement.text());
	        		if(done == 'YES'){
	        			activityElement.css('background-color','#66ff33');
	        		} else {
	        			activityElement.css('background-color','red');
	        		}
	        	} else {
	        		alert(data.message);
	        	}
	        	activityDialog.dialog("close");
	        },
	        error: function (xhr) {
	        } 
	    });
	}
	$('td[id^="tg"]').on('click',function(){
		$('#merchantId').val($(this).parent().attr('merchantId'));
		$('#times').val($(this).attr('id').split('_')[1]);
		var kaiyeTime = $(this).parent().find('input[name^="ky"]').val();
		if(kaiyeTime==''){
			alert('请先选择装修时间');
		} else {
			activityDialog.dialog('option','title', "设置"+$(this).text()+'活动').dialog("open");
			activityElement = $(this);
		}
	});
	//渲染活动
	$("tr[name='activity-render']").each(function(index,element){
		var merchantId = $(this).attr('merchantId');
		var activityElement = $(this);
		var kaiyeTime = activityElement.find('input[name^="ky"]').val();
		$.ajax({
		    type: "POST",
		    url: "/activity/getActivitysByMerchant.json",
		    data: {merchantId:merchantId},
		    success: function (data) {
		    	//获得开业时间
		    	var kaiyeDate = null;
		    	if(kaiyeTime!=''&&kaiyeTime!=null){
					console.info('开业时间：'+kaiyeTime);
					kaiyeDate = new moment(kaiyeTime);
				}
		    	//获得开业时间月份
		    	
		        console.info('通过商户ID：'+merchantId+'，获得内容：'+JSON.stringify(data));
		        if(data.length>0){
		        	renderActivity(activityElement,data,kaiyeDate);
		        }
		    },
		    dataType: "json"
		})
	});
});
/**
 * 
 * @param fromdb 数据库获取的集合数据
 * @param kaiyeDate 开业时间
 * @returns
 */
function renderActivity(activityElement,fromdb,kaiyeDate){
	var kaiyemonty = null,st1,st2,st3;
	if(kaiyeDate != null)
		kaiyemonty = kaiyeDate.month()+1;
	$.each(fromdb,function(i,json){
		var temp = new moment(json.tgTime);
		var activeTime = temp.month()+1
		findDivByTime(
				activityElement,
				activeTime-kaiyemonty,
				json.times,
				json.activityDone
			);
	});
}
/**
 * 
 * @param activityElement 活动节点
 * @param month 第几个月
 * @param times 第几次
 * @returns 找到的dom对象
 */
function findDivByTime(activityElement,month,times,done){
	var finded = null;
	activityElement.find('td[id^="tg"]').each(function(index,element){
    	if($(this).attr('id').indexOf('tg'+month+'_'+times)>=0){
    		finded = $(this);
    		return;
    	}
    });
	if(finded != null){
		if(done == 'YES'){
			finded.css('background-color','#66ff33');
		} else {
			finded.css('background-color','red');
		}
		finded.unbind('click');
	}
	return finded;
}

function parseDate2String(date){
	return moment(date).format('YYYY-MM-DD');
}
function addUser() {
	var valid = true;
	$("#merchantForm").submit();
	return valid;
}